﻿using UnityEngine;
using System.Collections;
using UnityEngine.UI;

/// <summary>
/// 显示背包
              /// </summary>
public class BackpackManager : MonoBehaviour {
	[SerializeField] GameObject itemCanvas;
	[SerializeField] Transform itemPos;
	[SerializeField] Text introText;
	int curItemIndex = 0;
	GameObject curItemShown;
	Backpack bag;

	public static BackpackManager _instance;
	// Use this for initialization
	void Start () {
		bag = Backpack._instance;
		itemCanvas.SetActive (false);
		_instance = this;
	}
	
	// Update is called once per frame
	void Update () {
		if (bag.Count <= 0) {
			HideItemCanvas ();
		}
		if (MyInput.GetInputOfType (InputType.SHOW_BACKPACK)) {
			if (bag.Count > 0) {
				if (itemCanvas.activeSelf) {
					HideItemCanvas ();
				} else {
					ShowItemCanvas ();
				}
			}
		}
		if (itemCanvas.activeSelf) {
			if (MyInput.GetInputOfType (InputType.SHOW_PREVIEW_ITEM)) {
				if (curItemIndex > 0) {
					ShowOneItem (--curItemIndex);
				}
			} else if (MyInput.GetInputOfType (InputType.SHOW_NEXT_ITEM)) {
				if (curItemIndex < bag.Count-1) {
					ShowOneItem (++curItemIndex);
				}
			}
		}
	}

	/// <summary>
	/// 将带有TaskItem的物品添加进背包中，并显示背包UI
	/// </summary>
	/// <param name="taskItem">Task item.</param>
	public void addItem(TaskItem taskItem){
		curItemIndex = bag.AddItem (taskItem);
		ShowItemCanvas ();
		ItemManager.DestroyItem (taskItem.Name);
	}

	/// <summary>
	/// 获取当前凝视的任务物体脚本TaskItem
	/// </summary>
	/// <returns>The task item gazed.</returns>
	/*TaskItem GetTaskItemGazed(){
		GameObject objGazed = MyInput.GetObjGazed ();
		if (objGazed != null) {
			TaskItem taskItem = objGazed.GetComponent<TaskItem> ();
			if (taskItem == null) {
				//TaskItem一般都是挂在模型的父物体上
				if(objGazed.transform.parent !=null){
					taskItem = objGazed.transform.parent.GetComponent<TaskItem> ();
				}
			}
			return taskItem;
		}
		return null;
	}*/
	///显示背包UI
	void ShowItemCanvas(){
		itemCanvas.SetActive (true);
		if (curItemIndex >= bag.Count) {
			curItemIndex = bag.Count - 1;
		}
		ShowOneItem (curItemIndex);
	}
	///隐藏背包UI
	void HideItemCanvas(){
		itemCanvas.SetActive (false);
	}

	///生成一个物品来显示
	GameObject ShowOneItem(int index){
		if (bag.Count <= 0) {
			return null;
		}
		return ShowOneItem (bag [index]);
	}
	///生成一个物品来显示
	GameObject ShowOneItem(TaskItem ti){
		if (curItemShown != null) {
			Destroy (curItemShown);
		}
		curItemShown = GameObject.Instantiate (bag.getPrefab(ti), itemPos.position, itemPos.rotation) as GameObject;
		curItemShown.SetActive (true);
		curItemShown.transform.parent = itemPos;
		introText.text = ti.Intro;
		curItemShown.transform.localScale *= ti.showScale;
		foreach (Collider col in curItemShown.GetComponentsInChildren<Collider>()) {
			Destroy (col);
		}
		foreach (TaskItem eachTI in curItemShown.GetComponentsInChildren<TaskItem>()) {
			Destroy (eachTI);
		}
		return curItemShown;
	}
}
